package cn.jsu.oj.dispatchServer.utils;

import org.springframework.core.io.Resource;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author ahtonc
 */
public class AnnotationPackageScanUtil {
    public final static String fileName;

    static {
        fileName = Objects.requireNonNull(AnnotationPackageScanUtil.class.getClassLoader().getResource("")).getFile();
    }

    public static List<Class<?>> scanPackage(String pkg, Class<? extends Annotation> clazz) {
        List<Class<?>> list = new ArrayList<>();
        try {
            Resource[] resources = ClassPathFileUtil.getClassFileResourcesByPackageName(pkg);
            for (Resource resource : resources) {
                if (!ClassPathFileUtil.isDirectory(resource)) {
                    String filePath = resource.getURL().getFile().substring(fileName.length()).replace(".class", "");
                    Class<?> c = Class.forName(filePath.replaceAll("/", "."));
                    if (c.getAnnotation(clazz) != null) {
                        list.add(c);
                    }
                }
            }
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
        return list;
    }
}
